package com.example.androidshixi;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class MyArticlesActivity extends AppCompatActivity {
    private ListView articleListView;
    private List<Article> myArticleList;
    private UserSessionManager sessionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_articles);

        articleListView = findViewById(R.id.article_list_view);
        sessionManager = new UserSessionManager(this);
        myArticleList = new ArrayList<>();

        // 接收传递过来的文章列表
        ArrayList<Article> allArticles = getIntent().getParcelableArrayListExtra("articles");
        if (allArticles != null) {
            // 从文章列表中筛选当前用户发布的文章
            for (Article article : allArticles) {
                if (article.getAuthor().equals(sessionManager.getLoggedInUsername())) {
                    myArticleList.add(article);
                }
            }
        }

        ArrayAdapter<Article> adapter = new ArrayAdapter<>(this, R.layout.article_item, R.id.article_title_text_view, myArticleList);
        articleListView.setAdapter(adapter);

        // 处理文章列表项点击事件
        articleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Article article = myArticleList.get(position);
                Intent intent = new Intent(MyArticlesActivity.this, ArticleDetailActivity.class);
                intent.putExtra("title", article.getTitle());
                intent.putExtra("author", article.getAuthor());
                intent.putExtra("time", article.getTime().getTime());
                intent.putExtra("content", article.getContent());
                startActivity(intent);
            }
        });
    }
}